#!/usr/bin/env python3
import base64
import hashlib
import hmac
import urllib
import requests
import json
import sys
import time

secret = "SECe7ff4fda294b52b101180565894afa43c5614f7fad7620978393bccab1c31557"
log_file = "/var/log/zabbix/zabbix_script_dingding.log"
api_url = "https://oapi.dingtalk.com/robot/send?access_token=fe122e1f8586f8a79e7f2de27fdd0c45aa46698121bd7a57ce9e981e7fb4404e"

headers = {'Content-Type': 'application/json;charset=utf-8'}
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

def log(info):
    try:
        f = open(log_file, 'a+')
        f.write(info)
        f.close()
    except IOError:
        print("Error: 没有找到文件或读取文件失败")


def info_format():
    new_info = ""
    temp_info = str(sys.argv[3]).split('\n')
    print(temp_info)
    for i in temp_info:
        new_info += "- " + str(i) + "\n>"
        print(new_info)
    return new_info


def send_msg(mobiles, title, message):

    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))


    # 构造带签名的请求URL
    signed_url = f"{api_url}&timestamp={timestamp}&sign={sign}"
    mobiles = "19939663307"
    level = sys.argv[4]
    status = sys.argv[5]

    # 定义字典映射
    level_title_map = {
        "0": f"<font color=\'#a8aeb6\'>{title}</font>",
        "1": f"<font color=\'#5795ee\'>{title}</font>",
        "2": f"<font color=\'#e5ad1a\'>{title}</font>",
        "3": f"<font color=\'#e56a1a\'>{title}</font>",
        "4": f"<font color=\'#d62314\'>{title}</font>",
        "5": f"<font color=\'#991308\'>{title}</font>",
        "99": f"<font color=\'#04c20a\'>{title}</font>"
    }
    if status == "1":
        new_title = level_title_map.get(level, title)
    else:
        new_title = level_title_map.get("99", title)

    json_text = {
        "msgtype": "actionCard",
        "actionCard": {
            "title": title,
            "text": f"#### {new_title}\n> {message}\n  @{mobiles}",
            "btnOrientation": "1",
            "btns": [
                {
                    "title": "拓扑图",
                    "actionURL": "https://zabbix.jieheyun.cn/zabbix.php?action=map.view"
                },
                {
                    "title": "忽略",
                    "actionURL": "https://zabbix.jieheyun.cn/zabbix.php?action=problem.view"
                }
            ]
        },
        "at": {
            "atMobiles": [
                mobiles
            ],
            "isAtAll": False
        }
    }

    r = requests.post(signed_url, data=json.dumps(json_text), headers=headers).json()
    code = r["errcode"]
    # 打印返回的JSON数据

    #print (code)
    if code == 0:
        log(current_time + ":消息发送成功 返回码:" + str(code) + "\n")
    else:
        log(current_time + ":消息发送失败 返回码:" + str(code) + "\n")
        exit(3)


if __name__ == '__main__':
    print("test")
    user = sys.argv[1]
    subject = sys.argv[2]
    text = info_format()

    send_msg(user, subject, text)
